#include "gardener.h"

Gardener::Gardener(QObject *parent) : QObject(parent)
{}

Gardener::~Gardener()
{
    stopReceiver();
}

void Gardener::startReceiver()
{
    receiver=new BaseReceiver;
    connect(receiver,&BaseReceiver::received,
            this,&Gardener::onReceived);
    connect(&recvThread,&QThread::finished,
            &QObject::deleteLater);
    receiver->moveToThread(&recvThread);
    recvThread.start();
}

void Gardener::stopReceiver()
{
    recvThread.quit();
    recvThread.wait();
}

void Gardener::onReceived(QByteArray data)
{
    if(data.contains(':'))
    {
        QList<QByteArray> items=data.split(':');
        qDebug() << items.first();
        qDebug() << items.last();
        if(items.last() == "quit")
        {
            QCoreApplication::quit();
        }
        return;
    }

    QJsonDocument doc=QJsonDocument::fromJson(data);
    if(doc.isObject())
    {
        QJsonObject obj=doc.object();
        QString target=obj.value("target").toString();
        QString command=obj.value("command").toString();
        qDebug() << target;
        qDebug() << command;
        if(command == "quit")
        {
            QCoreApplication::quit();
        }
    }
}
